package org.simplextensions.ui.menu;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

import org.simplextensions.ui.IApplicationWindow;
import org.simplextensions.ui.SwingApplicationWindow;

public class WindowMenuManager extends MenuManager {

	private final IApplicationWindow applicationWindow;
	private final String menuId;
	private MenuExtensionPoint mep;

	private JMenuBar menuBar;

	private JFrame jFrame;

	public WindowMenuManager(IApplicationWindow applicationWindow, JFrame jFrame, String menuId) {
		this.applicationWindow = applicationWindow;
		this.menuId = menuId;
		this.mep = applicationWindow.getMenuExtensionPoint();
		this.jFrame = jFrame;

		this.jFrame.setJMenuBar(getMenuBar());
	}

	public WindowMenuManager(SwingApplicationWindow applicationWindow, String menuId) {
		this(applicationWindow, applicationWindow.getjFrame(), menuId);

	}

	public JMenuBar getMenuBar() {
		if (menuBar == null) {
			MenuExtensionMetadata menu = mep.getMenu(menuId);
			menuBar = new JMenuBar();

			for (MenuExtensionMetadata memd : menu.getSubItems()) {
				JMenu createdSubMenu = createMenu(memd);
				if (createdSubMenu != null) {
					menuBar.add(createdSubMenu);
				}
			}
		}
		return menuBar;
	}

	protected JMenuItem createMenuItems(MenuExtensionMetadata submemd, JMenu parentMenu, IActions executable) {
		JMenuItem createActions = super.createMenuItems(submemd, parentMenu, executable);
		if (executable instanceof IApplicationWindowActions) {
			((IApplicationWindowActions) executable).init(applicationWindow);
		}
		return createActions;
	}

	protected JMenuItem createMenuItem(final MenuExtensionMetadata submemd, final IAction executable) {
		JMenuItem createMenuItem = super.createMenuItem(submemd, executable);
		if (executable instanceof IApplicationWindowAction) {
			((IApplicationWindowAction) executable).init(applicationWindow);
		}
		return createMenuItem;
	}
}